$(document).ready(function() {
    var VAL ={
        NORMAL     : "0000000"  ,
        EVT_USER   : $("#userId").text(),
        T_FBPINQOPE  : "FBPINQOPE"  ,
        T_FIPINQSHT  : "FIPINQSHT",
        T_FBPBISOPE	 : 'FBPBISOPE',
        T_FBPBISTOL  : 'FBPBISTOL',
        T_FBPBOXMAG	 : 'FBPBOXMAG',
        T_FBPBISPTH  : 'FBPBISPTH',
        T_FIPINQBOX  : 'FIPINQBOX',
        T_FPPMOVEIN	 : 'FPPMOVEIN'
    };
    var domObj = {
        window : $(window),
        cassetteListDiv : $("#cassetteListDiv"),
        cassetteListGrd : $("#cassetteListGrd"),
        cassetteGrdPg : "#cassetteGrdPg",
        glassListDiv : $("#glassListDiv"),
        glassListGrd : $("#glassListGrd"),
        glassGrdPg : $("#glassGrdPg")
    };
    /**
     * All controls's jquery object/text
     * @type {Object}
     */
    var controlsQuery = {
        W                  : $(window)             ,
        opeSelect          : $("#opeSelect")       ,
        toolIdSel          : $("#toolIdSel")      ,
        toolPortIdSel      : $("#toolPortIdSel")      ,
        cusOrderIdSel      : $("#cusOrderIdSel")      ,
        mdlIdSel  		   : $("#mdlIdSel"),
        cusIdSel           : $("#cusIdSel")
    };

    /**
     * All button's jquery object
     * @type {Object}
     */
    var btnQuery = {
        query  : $("#query_btn"),
        moveIn : $("#move_in_btn"),
        fresh  : $("#fresh_btn")
    };

    /**
     * All tool functions
     * @type {Object}
     */
    var toolFunc = {
        resetJqgrid :function(){
//            controlsQuery.W.unbind("onresize");
//            controlsQuery.mainGrd.grdId.setGridWidth(controlsQuery.mainGrd.fatherDiv.width()*0.90);
//            controlsQuery.W.bind("onresize", this);
        },
        clearInput : function(){
            $("select").empty();
            $("input").val("");
//        	SelectDom.setSelect($("select"), "", "");       
        },
        setOpeSelectDate : function(dataCnt, arr, selVal, selVal2, selTxt, selVal3, queryObj){
            var i, realCnt;

            queryObj.empty();
            realCnt = parseInt( dataCnt, 10);
            queryObj.append("<option value=''></option>");
            if( realCnt == 1 ){
                queryObj.append("<option value="+ arr[selVal] + "@" + arr[selVal2] +"@"+arr[i][selVal3]+">"+ arr[selTxt] +"</option>");
            }else if( realCnt > 1 ){
                for( i = 0; i < realCnt; i++ ){
                    queryObj.append("<option value="+ arr[i][selVal] + "@" + arr[i][selVal2] + "@"+arr[i][selVal3]+">"+ arr[i][selTxt] +"</option>");
                }
            }
            queryObj.select2({
                theme : "bootstrap"
            });
        },
        iniOpeSelect : function(){
            SelectDom.setSelect($("select"), "", "");
            var inObj, outObj;
            var ope_arr = new Array();
            inObj = {
                trx_id      : VAL.T_FBPBISOPE,
                action_flg  : 'L'
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                for(var i=0;i<outObj.tbl_cnt;i++){
                    if(outObj.oary[i].tool_run_mode != "UPK"){
                        ope_arr.push(outObj.oary[i]);
                    }
                }
                toolFunc.setOpeSelectDate(ope_arr.length, ope_arr, "ope_id", "ope_ver", "ope_id","tool_run_mode", controlsQuery.opeSelect);
            }
        },
        iniToolSel: function(){
            controlsQuery.toolIdSel.empty();
            var opeSelVal = $("#opeSelect option:selected").val();
            var selectedMode = opeSelVal.split("@")[2];
            var inObj, outObj;
            var iary = {
                tool_run_mode : selectedMode,
                tool_stat     : 'RUN',
                unit_typ      : 'MAIN'
            };
            inObj = {
                trx_id      : VAL.T_FBPBISTOL,
                action_flg  : 'H',
                iary		 : [iary]
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                SelectDom.addSelectArr(controlsQuery.toolIdSel, outObj.oaryB, "tool_id","tool_id","",true);
            }
            controlsQuery.toolIdSel.select2({
                theme : "bootstrap"
            });
        },
        iniPortSel: function(){
            controlsQuery.toolPortIdSel.empty();
            var toolSelVal = $("#toolIdSel option:selected").val();
            var inObj, outObj;
            var item = "port_id";
            var iary = {
                tool_id : toolSelVal,
                port_typ: 'L'
            }
            inObj = {
                trx_id    : VAL.T_FBPBISTOL,
                action_flg: 'I',
                iary	  : [iary]
            }
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                SelectDom.addSelectArr(controlsQuery.toolPortIdSel, outObj.oaryB, "port_id","port_id","",true);
            }
            controlsQuery.toolPortIdSel.select2({
                theme : "bootstrap"
            });

        },
        iniCassetteList:function(){
            $("#cassetteListGrd").jqGrid("clearGridData");
            $("#glassListGrd").jqGrid("clearGridData");
            var opeSelVal = $("#opeSelect option:selected").val();
            var opeId = opeSelVal.split("@")[0];
            var toolIdSel = $("#toolIdSel option:selected").val();
            var toolPortIdSel = $("#toolPortIdSel option:selected").val();
            if (!opeId) {
                showErrorDialog("","请选择站点！");
                return;
            }
            if (!toolIdSel) {
                showErrorDialog("","请选择机台！");
                return;
            }
            if (!toolPortIdSel) {
                showErrorDialog("","请选择端口！");
                return;
            }
            var oary = new Array();
            var inTrxObj ={
                trx_id     : VAL.T_FIPINQBOX,
                action_flg : 'B'        ,
                nx_ope_id_fk : opeId,
                tool_id : toolIdSel ,
                tool_port_id_fk: toolPortIdSel

            };
            var  outTrxObj = comTrxSubSendPostJson(inTrxObj);
            if(  outTrxObj.rtn_code == VAL.NORMAL ) {
                for(var i=0;i<outTrxObj.oary_box.length;i++){
                    if(outTrxObj.oary_box[i].box_stat == "WAIT" || outTrxObj.oary_box[i].box_stat == "INPR"){
                        oary.push(outTrxObj.oary_box[i]);
                    }
                }
                setGridInfo(oary,"#cassetteListGrd");
            }
        }
//        ,
//        setGlassGrdByBoxSel: function(){
//        	var rowId = $("#cassetteListGrd").jqGrid('getGridParam','selrow');
//        	var rowData = $("#cassetteListGrd").jqGrid("getRowData",rowId);
//        	if (rowData.box_id !=null) {
//        		var boxid = rowData.box_id;
//			}
//       	      
//       	   //给glassListGrd赋值
//       	   var outObj,inObj_Query;
//     	   var inObj_Query = {
//     					trx_id : VAL.T_FIPINQSHT,
//     					action_flg : 'C',
//     					box_id : boxid,
//     					prd_stat : 'WAIT'
//     				};
//     		outObj = comTrxSubSendPostJson(inObj_Query);
//    		if (outObj.rtn_code === VAL.NORMAL) {
//    			setGridInfo(outObj.oary_table, "#glassListGrd");
//    		}
//        
//        }
    };

    /**
     * All button click function
     * @type {Object}
     */
    var btnFunc = {
        //Query
        query_func : function(){
            toolFunc.iniCassetteList();
        },
        //Move in
        moveIn_func : function(){
            var iRow,
                selectRowIds,
                selectRowIdsLen,
                selectRow,
                box_id,
                ope_id,
                ope_ver,
                opeIndex,
//                user_id,
                movein_rc,
                inObj,
                outObj,
                selectBoxRowId,
                selectBoxRow;

            if(!$.trim(controlsQuery.opeSelect.val())){
                return false;
            }

            opeIndex = controlsQuery.opeSelect.val().indexOf("@");
            ope_id   = controlsQuery.opeSelect.val().substr(0, opeIndex);
            ope_ver  = controlsQuery.opeSelect.val().split("@")[1];
            tool_id  = controlsQuery.toolIdSel.val();
            port_id  = controlsQuery.toolPortIdSel.val();

            selectBoxRowId = domObj.cassetteListGrd.jqGrid('getGridParam','selrow');
            if(!selectBoxRowId){
                showErrorDialog("001","请选择要释放的箱号！");
                return false;
            }

            selectRowIds = domObj.glassListGrd.jqGrid('getGridParam','selarrrow');
            if(selectRowIds.length <= 0){
                showErrorDialog("02","请选择要入账的玻璃！");
                return false;
            }


            /*** 将Div实例化为modal窗体 ***/
            function diaLogRemarkFnc(){
                var rowData = domObj.cassetteListGrd.jqGrid("getRowData",selectBoxRowId);
                var box_id = rowData.box_id;
                var iary = new Array();
                selectRowIds = domObj.glassListGrd.jqGrid('getGridParam','selarrrow');
                selectRowIdsLen = selectRowIds.length;

                var remarkTxt = $("#remarkDialog_inputTxt").val();
                for( iRow = 0; iRow<selectRowIdsLen; iRow++){
                    selectRow = domObj.glassListGrd.jqGrid("getRowData", selectRowIds[iRow]);
                    var iary_info={
                        slot_no:selectRow['slot_no'],
                        prd_seq_id:selectRow['prd_seq_id']
                    };
                    iary.push(iary_info);

                }
                inObj = {
                    trx_id     : VAL.T_FPPMOVEIN,
//                        evt_usr    : VAL.EVT_USER,
                    evt_usr    : 'CMJ'  ,
                    box_id     : box_id        ,
//                        cr_ope_id  : ope_id        ,
//                        cr_ope_ver : ope_ver,
                    tool_id : tool_id,
                    port_id : port_id,
                    sht_ope_msg: remarkTxt,
                    opi_ope_flg :"Y",
                    iary	: iary
                };
                outObj = comTrxSubSendPostJson(inObj);
                if(outObj.rtn_code == VAL.NORMAL) {
                    selectRow['rc'] = "Y";
                    domObj.glassListGrd.jqGrid("setRowData", selectRowIds[iRow], selectRow);
                    showSuccessDialog("入账成功！");
                    domObj.glassListGrd.jqGrid('clearGridData');
                    btnFunc.query_func();
                }else{
                    selectRow['rc'] = "N";
                    domObj.glassListGrd.jqGrid("setRowData", selectRowIds[iRow], selectRow);
                }
                $('#remarkDialog').modal("hide");
            }

            $('#remarkDialog').modal({
                backdrop:'static',
                keyboard:false,
                show:false
            });
            $('#remarkDialog').unbind('shown.bs.modal');
            $("#remarkDialog_moveinBtn").unbind('click');

            $('#remarkDialog').bind('shown.bs.modal');
            $('#remarkDialog').modal("show");
            $("#remarkDialog_inputTxt").val("");
            $("#remarkDialog_moveinBtn").bind('click',diaLogRemarkFnc);
            $("#remarkDialog input").attr({'disabled':false});

        },
        //fresh func
        fresh_func:function(){
            location.reload();
        },
        getPrdInf:function(box_id){
            var inTrxObj ={
                trx_id     : VAL.T_FIPINQBOX,
                action_flg : 'I'        ,
                box_id : box_id
            };
            var  outTrxObj = comTrxSubSendPostJson(inTrxObj);
            if(  outTrxObj.rtn_code == VAL.NORMAL ) {
                controlsQuery.cusOrderIdSel.val(outTrxObj.wo_id_fk);
                controlsQuery.mdlIdSel.val(outTrxObj.mdl_id_fk);
                controlsQuery.cusIdSel.val(outTrxObj.cus_id_fk);
                //给glassListGrd赋值
                setGridInfo(outTrxObj.oaryC, "#glassListGrd");
            }
        }
    };

    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        btnQuery.query.click(function(){
            btnFunc.query_func();
        });
        btnQuery.moveIn.click(function(){
            btnFunc.moveIn_func();
        });
        btnQuery.fresh.click(function(){
            btnFunc.fresh_func();
        });
    };

    /**
     * grid  initialization
     */
    var iniGridInfo = function(){
        var cassetteGrdInfoCM = [
            {name: 'box_id',   		index: 'box_id',   		label: CASSETTE_NO_TAG    , width: CASSETTE_ID_CLM},
            {name: 'box_stat', 		index: 'box_stat',		label: STATUS_TAG    , 		width: STATUS_CLM},
            {name: 'prd_qty',    	index: 'prd_qty',   	label: GLASS_NUM_TAG  , 	width: GLASS_NUM_CLM},
            {name: 'tool_id_fk',    index: 'tool_id_fk',   	label: TOOL_ID_TAG  , 		width: TOOL_ID_CLM}
        ];
        domObj.cassetteListGrd.jqGrid({
            url:"",
            datatype:"local",
            mtype:"POST",
            height:375,
            shrinkToFit:true,
            scroll:true,
            autowidth:true,
            rownumWidth : true,
            resizable : true,
            rowNum:40,
            loadonce:true,
            fixed:true,
            viewrecords:true,
//            multiselect : true,
            pager : domObj.cassetteGrdPg,
            colModel: cassetteGrdInfoCM,
            onSelectRow: function(id){
                var rowData = $(this).jqGrid("getRowData",id);
//            	console.log(rowData);
                if (rowData.box_id !=null) {
                    btnFunc.getPrdInf(rowData.box_id);
                }
            }

        });
    }

    var glassGrdInfoCM = [
        {name: 'slot_no',       index: 'slot_no',    label: SUB_SITE_TAG,       width: SUB_SITE_CLM},
        {name: 'prd_seq_id', 	index: 'prd_seq_id', label: SHEET_ID_TAG, 	    width: SHEET_ID_CLM},
        {name: 'prd_stat',  	index: 'prd_stat',   label: GLASS_STATUS_TAG,   width: SHEET_STATUS_CLM},
        {name: 'wo_id_fk',      index: 'wo_id_fk',   label: SO_ID_TAG  ,        width: SO_NO_CLM},
        {name: 'mdl_id_fk',     index: 'mdl_id_fk',  label: PRODUCT_ID_TAG  ,   width: PRODUCT_ID_CLM},
        {name: 'prd_qty',       index: 'prd_qty',    label: PANEL_NUM_TAG  ,    width: PANEL_NUM_CLM}
    ];
    domObj.glassListGrd.jqGrid({
        url:"",
        datatype:"local",
        mtype:"POST",
        height:375,
        width:domObj.glassListDiv.width(),
        shrinkToFit:true,
        autowidth:true,
        scroll:true,
        rownumWidth : true,
        resizable : true,
        rowNum:40,
        loadonce:true,
        fixed:true,
        viewrecords:true,
        multiselect : true,
        pager : domObj.glassGrdPg,
        colModel: glassGrdInfoCM,
        gridComplete: function() {
            var rowIds = jQuery("#listTable").jqGrid('getDataIDs');
//                for(var k=0; k<rowIds.length; k++) {
//                   var curRowData = jQuery("#listTable").jqGrid('getRowData', rowIds[k]);
//                   var curChk = $("#"+rowIds[k]+"").find(":checkbox");
//                   curChk.attr('name', 'checkboxname');   //给每一个checkbox赋名字
//                   curChk.attr('value', curRowData['MY_ID']);   //给checkbox赋值
//                   curChk.attr('title', curRowData['NAME'] );   //给checkbox赋予额外的属性值
//                }
        }

    });



    /**
     * Ini contorl's data
     */
    var iniContorlData = function(){
        toolFunc.clearInput();

        //Ope info
        toolFunc.iniOpeSelect();

        //Tool info
//        toolFunc.iniToolSel();

        //Port info
//        toolFunc.iniPortSel();

        //CassetteList info
//        toolFunc.iniCassetteList();

        controlsQuery.opeSelect.change(function(){
            toolFunc.iniToolSel();
        });
        controlsQuery.toolIdSel.change(function(){
            toolFunc.iniPortSel();
        });
    };

    /**
     * Ini view, data and action bind
     */
    var initializationFunc = function(){
        iniGridInfo();
        iniButtonAction();
        iniContorlData();
    };

    initializationFunc();
    //模态框拖动
    $(".modal-content").draggable();
    //表格自适应
    function resizeFnc(){
        //1
        var offsetBottom,divWidth,offsetBottom1,divWidth1;
        divWidth = $("#cassetteControlsDiv").width();
        offsetBottom =  $(window).height() - $("#cassetteListDiv").offset().top;
        $("#cassetteListDiv").height(offsetBottom * 0.95);
        $("#cassetteListGrd").setGridWidth(divWidth * 0.99);
        $("#cassetteListGrd").setGridHeight(offsetBottom * 0.99 - 51);
        divWidth1 = $("#glassControlsDiv").width();
        offsetBottom1 =$(window).height() - $("#glassListDiv").offset().top;
        $("#glassListDiv").height(offsetBottom1 * 0.95);
        $("#glassListGrd").setGridWidth(divWidth1 * 0.99);
        $("#glassListGrd").setGridHeight(offsetBottom1 * 0.99 - 51);

    };
    resizeFnc();
    $(window).resize(function() {
        resizeFnc();
    });

});

